package Test1;
import java.io.*;

public class Person implements Serializable {
    private String name;
    private transient int age; // age字段被标记为transient

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 省略其他代码...

    public static void main(String[] args) {
        Person person = new Person("John", 30);

        // 序列化对象
        try {
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化对象
        try {
            FileInputStream fileIn = new FileInputStream("person.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Person serializedPerson = (Person) in.readObject();
            in.close();
            fileIn.close();

            System.out.println("Name: " + serializedPerson.name); // 输出 Name: John
            System.out.println("Age: " + serializedPerson.age);   // 输出 Age: 0 (因为age字段是transient)
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

